import {Injectable, ExecutionContext } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Repository } from "typeorm";
import { TokenEntity } from "../../ShareModule/entities/token.entity";
import { Reflector } from "@nestjs/core";
import { Observable } from "rxjs";

@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt"){
    constructor(
        private readonly tokenRepository:Repository<TokenEntity>,
        private readonly reflector:Reflector,
    ){
        super();
    }

    canActivate(
        context:ExecutionContext
    ): boolean | Promise<boolean> | Observable<boolean> {
        const roles = this.reflector.get<string>('roles',context.getHandler());
        if(roles && roles.length){
        //add custom authentication
        //通过请求头中携带的参数token来查询数据库。如果token存在，则校验通过，否则校验失败；
        const request = context.switchToHttp().getRequest();
        let token = request.headers.authorization;

        if(token) {
            token = token.replace("Bearer","");
            return this.findOne(token).then(res =>{
                if(res) return true;
            })
        }

        return super.canActivate(context);
        }
    }

    async findOne(token:string) {
        try{
            return await this.tokenRepository.findOne({token});
        }catch(err){
            throw err;
        }
    }

}